package com.huang825172.sbog.Tabs.Create.SelectPage.Store;

import android.content.Context;
import android.util.Base64;
import android.util.Log;

import com.baidubce.BceClientException;
import com.baidubce.BceServiceException;
import com.baidubce.auth.DefaultBceCredentials;
import com.baidubce.services.bos.BosClient;
import com.baidubce.services.bos.BosClientConfiguration;
import com.baidubce.services.bos.model.PutObjectResponse;
import com.google.gson.Gson;
import com.huang825172.sbog.BaseFlux.Action.BaseAction;
import com.huang825172.sbog.BaseFlux.Store.BaseStore;
import com.huang825172.sbog.GlobalManager.LoginStateManager;
import com.huang825172.sbog.R;
import com.huang825172.sbog.Tabs.Create.SelectPage.Action.CommitAction;
import com.huang825172.sbog.Tabs.Create.SelectPage.Action.GetVideoAction;
import com.huang825172.sbog.Tabs.Create.SelectPage.Store.Datas.uploadVideo;
import com.huang825172.sbog.Tabs.Create.SelectPage.Store.Datas.uploadVideoRes;
import com.huang825172.sbog.Util.TAGs;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class Store extends BaseStore {

    private List<String> videoFilePaths;
    private boolean videoSelected = false;
    private LoginStateManager stateManager;

    public Store(Context context) {
        super(context);
        stateManager = new LoginStateManager(context);
    }

    @Override
    public List<String> getActionLabels() {
        List<String> labels = new ArrayList<>();
        labels.add("SelectPageGetVideoAction");
        labels.add("SelectPageCommitAction");
        return labels;
    }

    @Override
    public void changeData(BaseAction action) {
        super.changeData(action);
        switch (action.getLabel()) {
            case "SelectPageGetVideoAction": {
                GetVideoAction act = (GetVideoAction) action;
                videoFilePaths = act.getFilePaths();
                videoSelected = true;
                notifyDataChanged("SelectPageGetVideoAction");
                break;
            }
            case "SelectPageCommitAction": {
                CommitAction act = (CommitAction) action;
                upLoadVideo(videoFilePaths.get(0), act.getText(), act.getTag());
                break;
            }
            default:
                break;
        }
    }

    public void upLoadVideo(final String filePath, final String text, final String tag){
        if(filePath != null){
            if(!getExt(filePath).equals("mp4")){
                notifyDataChanged("SelectPageFileExtError");
                return;
            }

            String ak = new String(Base64.decode(context.getString(R.string.bosAk), Base64.DEFAULT));
            String sk = new String(Base64.decode(context.getString(R.string.bosSk), Base64.DEFAULT));
            String ep = new String(Base64.decode(context.getString(R.string.bosEp), Base64.DEFAULT));
            String linkHead = new String(Base64.decode(context.getString(R.string.bosLinkHead), Base64.DEFAULT));
            final String bk = context.getString(R.string.bosBk);

            long timeStamp = System.currentTimeMillis();
            final String fileKey = Long.toString(timeStamp) + ".mp4";

            final String fileLink = linkHead + fileKey;

            final BosClientConfiguration config = new BosClientConfiguration();
            config.setCredentials(new DefaultBceCredentials(ak, sk));
            config.setEndpoint(ep);
            final BosClient client = new BosClient(config);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        File file = new File(filePath);
                        PutObjectResponse putObjFromFile = client.putObject(bk, fileKey, file);
                        Log.d(TAGs.INFO, putObjFromFile.getETag());
                        Log.d(TAGs.INFO, fileLink);
                        notifyDataChanged("SelectPageFileUploaded");

                        final Gson gson = new Gson();
                        uploadVideo info = new uploadVideo(stateManager.getLoginToken(),fileLink,text,tag);
                        final String infoStr = gson.toJson(info);
                        Retrofit retrofit = new Retrofit.Builder()
                                .baseUrl(context.getString(R.string.server_baseUrl))
                                .build();
                        Interfaces request = retrofit.create(Interfaces.class);
                        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),infoStr);
                        Call<ResponseBody> call = request.uploadVideo(body);
                        Log.d(TAGs.INFO, infoStr);
                        call.enqueue(new Callback<ResponseBody>() {
                            @Override
                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                try {
                                    String resStr = response.body().string();
                                    uploadVideoRes resObj = gson.fromJson(resStr, uploadVideoRes.class);
                                    if (resObj.code == 200){
                                        notifyDataChanged("SelectPageVideoPostSuccess");
                                    }
                                    Log.d(TAGs.INFO, resObj.msg);
                                }catch (Exception e){
                                    e.printStackTrace();
                                    Log.e(TAGs.ERROR, e.getMessage());
                                    notifyDataChanged("SelectPageVideoPostFail");
                                }
                            }

                            @Override
                            public void onFailure(Call<ResponseBody> call, Throwable t) {
                                t.printStackTrace();
                                notifyDataChanged("SelectPageVideoPostFail");
                            }
                        });
                    } catch (BceServiceException e) {
                        System.out.println("Error ErrorCode: " + e.getErrorCode());
                        System.out.println("Error RequestId: " + e.getRequestId());
                        System.out.println("Error StatusCode: " + e.getStatusCode());
                        System.out.println("Error Message: " + e.getMessage());
                        System.out.println("Error ErrorType: " + e.getErrorType());
                        e.printStackTrace();
                        notifyDataChanged("SelectPageFileUploadFail");
                    } catch (BceClientException e) {
                        System.out.println("Error Message: " + e.getMessage());
                        e.printStackTrace();
                        notifyDataChanged("SelectPageFileUploadFail");
                    }
                }
            }).start();
        }
    }

    public List<String> getVideoFilePaths() {
        return videoFilePaths;
    }

    public static String getExt(String filename) {
        int index = filename.lastIndexOf(".");

        if (index == -1) {
            return null;
        }
        String result = filename.substring(index + 1);
        return result;
    }
}
